<?php

/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * Dao模块，采用PDO
 */
class Db extends Model {

    // dsn
    private $dsn = "mysql:host=localhost;dbname=test";
    // db
    private $db;
    // 单例 todo
    protected static $_instance = NULL;

    /**
     * 
     * @global type $config
     */
    public function __construct() {
        global $config;
        parent::__construct();
        $this->dsn = sprintf("mysql:host=%s;dbname=%s", $config->db['host'], $config->db['db']);
        $this->db = new PDO($this->dsn, $config->db['user'], $config->db['pass']);
        $this->db->exec("SET NAMES 'UTF8'");
    }

    /**
     *  
     * @param type $statement
     * @return type
     */
    public function query($statement, $fetchStyle = PDO::FETCH_ASSOC) {
        if (preg_match("/INSERT/is", $statement)) {
            // INSERT
            $this->db->exec($statement);
            return $this->db->lastInsertId();
        } else if (preg_match("/UPDATE|DELETE/is", $statement)) {
            // UPDATE|DELETE=
            return $this->db->exec($statement);
        } else {
            // SELECT
            $query = $this->db->prepare($statement);
            $query->execute();
            return $query->fetchAll($fetchStyle);
        }
    }

    /**
     * 
     * @param type $statement
     * @return type
     */
    public function exec($statement) {
        return $this->db->exec($statement);
    }

}
